package cn.yshujia.handler;

import cn.yshujia.utils.MinioUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author YShuJia
 * @create 2025/3/7
 * @description PathHandler
 */

public class PathHandler extends BaseTypeHandler<String> {
	@Override
	public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
		if (null != s) {
			s = s.replaceAll(MinioUtils.STATIC_DOMAIN, "");
		}
		preparedStatement.setString(i, s);
	}
	
	@Override
	public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
		return addPrefix(resultSet.getString(s));
	}
	
	@Override
	public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
		return addPrefix(resultSet.getString(i));
	}
	
	@Override
	public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
		return addPrefix(callableStatement.getString(i));
	}
	
	private String addPrefix(String s) {
		if (s == null) {
			return null;
		}
		String[] paths = s.split(",");
		if (paths.length > 0) {
			for (int i = 0; i < paths.length; i++) {
				paths[i] = MinioUtils.STATIC_DOMAIN + paths[i];
			}
			return String.join(",", paths);
		}
		return "";
	}
}
